<?php

/**
 * offer actions.
 *
 * @package    reduceri-cadouri
 * @subpackage offer
 * @author     Your name here
 */
class offerActions extends sfActions
{
  public function preExecute()
  {
    $request = sfContext::getInstance()->getRequest();
    
    if(!$request->getParameter('city_name'))
    {
      if($request->getCookie('city_name'))
      {
        $request->setParameter('city_name',$request->getCookie('city_name'));
      }
      else
      {
        $request->setParameter('city_name','all');
      }
    }
    
    if(!$this->city = CityPeer::retrieveBySlug($request->getParameter('city_name')))
    {
      $request->setParameter('city_name','all');
      $this->city = new City();
      $this->city->setName('Romania');
    }
    
    $this->getResponse()->setCookie('city_name', $request->getParameter('city_name'), time()+60*60*24*7);
    
    $this->city_name = $request->getParameter('city_name');
  }
  
  public function executeIndex(sfWebRequest $request)
  {
    $c = new Criteria();
    $c->addDescendingOrderByColumn(OfferPeer::CREATED_AT);
    if($request->getParameter('site_id'))
    {
      $c->add(OfferPeer::SITE_ID, $request->getParameter('site_id'));
    }
    if($request->getParameter('date'))
    {
      $c->add(OfferPeer::START_TIME, date("Y-m-d 00:00:00", strtotime($request->getParameter('date'))), Criteria::LESS_EQUAL);
      $c->add(OfferPeer::END_TIME, date("Y-m-d 00:00:00", strtotime($request->getParameter('date')) + 86400 - 1), Criteria::GREATER_THAN);
    }
    $pager = new sfPropelPager('Offer', 10);
    $pager->setCriteria($c);
    $pager->setPage($this->getRequestParameter('page', 1));
    $pager->init();
    $this->pager = $pager;
  }

  public function executeNew(sfWebRequest $request)
  {
    if($site_id = $request->getParameter('site_id'))
    {
      $offer = new Offer();
      $offer->setSiteId($site_id);
    }
    $this->form = new OfferForm($offer);
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new OfferForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer = OfferPeer::retrieveByPk($request->getParameter('id')), sprintf('Object Offer does not exist (%s).', $request->getParameter('id')));
    $this->form = new OfferForm($this->offer);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($Offer = OfferPeer::retrieveByPk($request->getParameter('id')), sprintf('Object Offer does not exist (%s).', $request->getParameter('id')));
    $this->form = new OfferForm($Offer);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $this->forward404Unless($Offer = OfferPeer::retrieveByPk($request->getParameter('id')), sprintf('Object Offer does not exist (%s).', $request->getParameter('id')));
    $Offer->delete();

    $this->redirect('offer/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $Offer = $form->save();
      
      //save in search
      $Offer->save(null, true);
      
      /*
      if($Offer->getOnSite())
      {
        $page_id = "182974521721759";
        
        $page_access_token = "116487325090582|326e6f23b427d938a1eefed7-533936499|182974521721759|dlRfci1bKYcfCYS8KhhOvWgduVg";
        
        // create a new cURL resource
        $ch = curl_init();

        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/".$page_id."/feed");
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        $data = array(
          'access_token' => $page_access_token,
          'link' => $this->getController()->genUrl($Offer->getRouteName().'?id='.$Offer->getId(), true),
          'picture' => 'http://reduceri-cadouri.ro/uploads/offers/small/'.$Offer->getImage()->getImage(),
          'name' => $Offer->getName(),
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // grab URL and pass it to the browser
        $response = curl_exec($ch);

        // close cURL resource, and free up system resources
        curl_close($ch);
      }
      */

      if($request->getParameter('next') == 'Save and add Images')
      {
        return $this->redirect('offer/images?offer_id='.$Offer->getId());
      }
      if($request->getParameter('next') == 'Save and add Locations')
      {
        return $this->redirect('offer/locations?offer_id='.$Offer->getId());
      }      
      $this->redirect('offer/edit?id='.$Offer->getId());
    }
  }
  
  public function executeImages(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer = OfferPeer::retrieveByPK($request->getParameter('offer_id')));
    
    $offer_image = new OfferImage();
    $offer_image->setOffer($this->offer);
    $this->form = new OfferImageForm($offer_image);
    
    if($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('offer_image'), $request->getFiles('offer_image'));
      if($this->form->isValid())
      {
        $offer_image = $this->form->save();
        if($offer_image->getUrl())
        {
          $offer_image->setImage($offer_image->getId().'.jpg');
          Utils::copyImageFromUrl($offer_image->getUrl(), $offer_image->getImage(), sfConfig::get('sf_upload_dir').'/offers/');
        }
        if($offer_image->getImage())
        {
          Utils::resizePhoto(sfConfig::get('sf_upload_dir').'/offers/'.$offer_image->getImage(), sfConfig::get('sf_upload_dir').'/offers/small/'.$offer_image->getImage(), 90, 90);
          Utils::resizePhoto(sfConfig::get('sf_upload_dir').'/offers/'.$offer_image->getImage(), sfConfig::get('sf_upload_dir').'/offers/medium/'.$offer_image->getImage(), 206, 206);
          unlink(sfConfig::get('sf_upload_dir').'/offers/'.$offer_image->getImage());
          $offer_image->save();
        }
        else
        {
          $offer_image->delete();
        }

        if($request->getParameter('next') == 'Save and add Locations')
        {
          return $this->redirect('offer/locations?offer_id='.$this->offer->getId());
        }
        if($request->getParameter('next') == 'Save and go to Offer')
        {
          return $this->redirect('offer/edit?id='.$this->offer->getId());
        }      
        return $this->redirect('offer/images?offer_id='.$this->offer->getId());
      }
    }
    
    $this->offer_images = $this->offer->getOfferImages();
  }
  
  public function executeDeleteImage(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer_image = OfferImagePeer::retrieveByPK($request->getParameter('id')));
    
    $this->offer_image->delete();
      
    return $this->redirect('offer/images?offer_id='.$this->offer_image->getOfferId());
  }
  
  public function executeLocations(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer = OfferPeer::retrieveByPK($request->getParameter('offer_id')));
    
    $offer_location = new OfferLocation();
    $offer_location->setOffer($this->offer);
    $this->form = new OfferLocationForm($offer_location);
    
    if($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('offer_location'));
      if($this->form->isValid())
      {
        $offer_location = $this->form->save();

        if($request->getParameter('next') == 'Save and add Images')
        {
          return $this->redirect('offer/images?offer_id='.$this->offer->getId());
        }
        if($request->getParameter('next') == 'Save and go to Offer')
        {
          return $this->redirect('offer/edit?id='.$this->offer->getId());
        }      
        return $this->redirect('offer/locations?offer_id='.$this->offer->getId());
      }
    }
    
    $this->offer_locations = $this->offer->getOfferLocations();
  }
  
  public function executeDeleteLocation(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer_location = OfferLocationPeer::retrieveByPK($request->getParameter('id')));
    
    $this->offer_location->delete();
      
    return $this->redirect('offer/locations?offer_id='.$this->offer_location->getOfferId());
  }
  
  public function executeOnsite(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer = OfferPeer::retrieveByPK($request->getParameter('id')));
    $this->offer->setOnSite($request->getParameter('value'));
    $this->offer->save();
    
    return $this->redirect('offer/index');
  }
  
  public function executeShow(sfWebRequest $request)
  {
    $this->forward404Unless($this->offer = OfferPeer::retrieveByPK($request->getParameter('id')));
    
    $this->getResponse()->setTitle(Utils::limitString($this->offer->getName(), 140, true));
    
    if($this->offer->getSiteId())
    {
      $description = '';
      if($this->offer->getDiscountPercent() >= 80)
      {
        $description .= 'Cadou oferit de ';
      }
      else
      {
        $description .= 'Reducere oferita de ';
      }
      $description .= $this->offer->getSite().' in '.$this->offer->getCitiesString();
      
      $this->getResponse()->addMeta('description', $description);
    }
  }
  
  public function executeReview(sfWebRequest $request)
  {
    $this->offers = OfferPeer::getOffersForReview();
    
    $this->categories = CategoryPeer::getAll();
  }
  
  public function executeAjaxreview(sfWebRequest $request)
  {
    if($offer = OfferPeer::retrieveByPK($request->getParameter('id')))
    {
      $new_offer_categories = $request->getParameter('offer_categories_'.$offer->getId());
      $old_offer_categories = array();
      $offer_categories = $offer->getOfferCategorys();
      foreach($offer_categories as $offer_category)
      {
        if(!in_array($offer_category->getCategoryId(), $new_offer_categories))
        {
          $offer_category->delete();
        }
        else
        {
          $old_offer_categories[] = $offer_category->getCategoryId();
        }
      }
      foreach($new_offer_categories as $category_id)
      {
        if(!in_array($category_id, $old_offer_categories))
        {
          $offer_category = new OfferCategory();
          $offer_category->setOfferId($offer->getId());
          $offer_category->setCategoryId($category_id);
          $offer_category->save();
        }
      }
      $offer->setDiscountPercent($request->getParameter('discount'));
      $offer->setReviewed(true);
      $offer->save();
    }
    
    return sfView::NONE;
  }
}
